<?php

namespace App\Modules\Apicrzs\Services\Water;

use App\Modules\Apicrzs\Entities\ApparatusModel;
use App\Modules\Apicrzs\Entities\UserScoreModel;
use App\Modules\Apicrzs\Entities\UsersModel;
use App\Modules\Apicrzs\Entities\UserWaterCardModel;
use App\Modules\Apicrzs\Services\BaseServices;
use App\Traits\CryptAES;
use Illuminate\Support\Facades\DB;

class WaterCardConsumeService extends BaseServices
{
    public function __construct(UserWaterCardModel $model)
    {
        $token = \request()->header('token');
        $user_info = CryptAES::decryptToken($token, 'user_grzq');
        $this->user_id = $user_info['data']['user_id'] ?? 0;
        $this->model = $model;
        $this->userScoreModel = new UserScoreModel();
    }
    public function getConsumeLists($params,UsersModel $user, float $amount, ?int $specifiedCardId = null)
    {

        $amount = $params['amount'];
        $specifiedCardId = $params['specifiedCardId']??null;

        return DB::transaction(function () use ($user, $amount, $specifiedCardId) {
            // 获取要使用的卡片
            $card = $specifiedCardId
                ? $this->getSpecifiedCard($user, $specifiedCardId)
                : $this->selectPriorityCard($user);

            // 执行扣费逻辑
            $this->processConsumption($card, $amount);

            // 记录消费日志
            $transaction = $this->logTransaction($card, $amount);

            return [
                'card' => $card,
                'transaction' => $transaction
            ];
        });
    }
    private function selectPriorityCard(UsersModel $user)
    {
        return $user->waterCards()
            ->active()
            ->valid()
            ->orderByRaw("FIELD(card_type, 'timed', 'count', 'prepaid')")
            ->lockForUpdate()
            ->firstOrFail();
    }

    private function processConsumption(UserWaterCardModel $card, float $amount)
    {
        $waterCard = $card->waterCard;

        switch ($waterCard->card_type) {
            case 'prepaid':
                $this->deductFromPrepaid($card, $amount);
                break;
            case 'count':
                $this->deductFromCountCard($card);
                break;
            case 'timed':
                $this->recordTimedUsage($card, $amount);
                break;
        }

        $this->updateCardStatus($card);
    }
    private function updateCardStatus(UserWaterCardModel $card)
    {
        $status = match ($card->waterCard->card_type) {
            'prepaid' => ($card->remaining_value <= 0) ? 'inactive' : 'active',
            'count' => ($card->remaining_value <= 0) ? 'expired' : 'active',
            'timed' => ($card->expiry_date->isPast()) ? 'expired' : 'active'
        };

        if ($status !== $card->card_status) {
            $card->update(['card_status' => $status]);
        }
    }
    private function deductFromPrepaid(UserWaterCardModel $card, float $amount)
    {
        if ($card->remaining_value < $amount) {
            throw new InsufficientBalanceException('储值卡余额不足');
        }

        $card->decrement('remaining_value', $amount);
        $card->update(['last_used' => now()]);
    }
    private function deductFromCountCard(UserWaterCardModel $card)
    {
        if ($card['remaining_value'] < 1) {
            throw new InsufficientCountException('次卡次数不足');
        }

        $card->decrement('remaining_value');
        $card->update(['last_used' => now()]);
    }
    private function recordTimedUsage(UserWaterCardModel $card, float $amount)
    {
        $usage = $amount * $card->waterCard->unit_price;

        WaterCardUsage::create([
            'user_card_id' => $card->id,
            'used_value' => $usage,
            'usage_time' => now()
        ]);
    }
}
